package com.kaikai.msg.model.dto;

import com.kaikai.msg.model.ao.EduEmail;
import com.kaikai.properties.SendMailProps;
import com.sun.mail.util.MailSSLSocketFactory;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.activation.DataHandler;
import javax.mail.*;
import javax.mail.internet.*;
import java.net.URL;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @return
 * @Author yujiankai
 * @Description 发送邮件
 * @date 2022/1/8 12:07
 */
public class SendMailDTO {
    private static Logger LOG = LoggerFactory.getLogger(SendMailDTO.class);

    private static String reg = ".+(.jpg|.png|.jpeg|.gif|.bmp)$";

    /**
     * 邮件对象
     */
    public MimeMessage mimeMessage;

    /**
     * session
     */
    private Session session;

    /**
     * properties
     */
    private static Properties properties = new Properties();

    /**
     * 附件添加的组件
     */
    private MimeMultipart multipart;


    /**
     * @Title: init 方法名
     * @Description: 初始化
     * @return void
     */
    private void init(SendMailProps sendMailProps, String authorization){
        properties.setProperty("mail.host", sendMailProps.getHost());
        properties.setProperty("mail.transport.protocol", "smtp");
        properties.setProperty("mail.smtp.port",sendMailProps.getPort());

        // 需要身份验证
        properties.setProperty("mail.auth", "true");
        //QQ邮箱
        if (StringUtils.isNotBlank(authorization)) {
            try {
                MailSSLSocketFactory sf = new MailSSLSocketFactory();
                sf.setTrustAllHosts(true);
                //设置开启ssl安全连接
                properties.put("mail.smtp.ssl.enable", "true");
                properties.put("mail.smtp.ssl.socketFactory", sf);
            } catch (Exception e) {
                System.out.println("链接失败");
                e.printStackTrace();
            }
            session = Session.getDefaultInstance(properties, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    // 获取第三方登录授权码
                    return new PasswordAuthentication(sendMailProps.getSenderName(),authorization);
                }
            });
        } else {
            session = Session.getDefaultInstance(properties);
        }
        // 控制台看发送日志的全过程  *****上环境要关掉
        session.setDebug(true);
        // 用session对象来创建并初始化邮件对象
        mimeMessage = new MimeMessage(session);
        // 生成组件的实例
        multipart = new MimeMultipart();
    }

    private SendMailDTO(SendMailProps sendMailProps,String to,String cc, String bcc,String mailBody,String mailSubject,List<String> attachments, String authorization) throws Exception {
        init(sendMailProps,authorization);
        mimeMessage.setFrom(new InternetAddress(sendMailProps.getSenderName(),"教育系统"));
        mimeMessage.setRecipients(Message.RecipientType.TO,InternetAddress.parse(to));
        if (StringUtils.isNotBlank(cc)) {
            mimeMessage.setRecipients(Message.RecipientType.CC,InternetAddress.parse(cc));
        }
        if (StringUtils.isNotBlank(bcc)) {
            mimeMessage.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc));
        }
        mimeMessage.setSubject(mailSubject);
        MimeBodyPart bodyPart = new MimeBodyPart();
        bodyPart.setContent(mailBody, "text/html;charset=gbk");
        multipart.addBodyPart(bodyPart);
        multipart.setSubType("related");
        if (CollectionUtils.isNotEmpty(attachments)) {
            for (int i = 0; i < attachments.size(); i++) {
                String attachment = attachments.get(i);
                addFileAffix(attachment);
            }
        }
        mimeMessage.setContent(multipart,"text/html;charset=gbk");
        mimeMessage.saveChanges();
        //连接发送
        Transport transport = session.getTransport();
        transport.connect(sendMailProps.getHost(),sendMailProps.getSenderName(),sendMailProps.getSenderAuth());
        transport.sendMessage(mimeMessage,mimeMessage.getAllRecipients());
        transport.close();
    }

    /**
     * @Title: entity 方法名
     * @Description: 邮件实体
     * @param
     * @return SendMailDTO
     */
    public static SendMailDTO sendMail (EduEmail sendAO) throws Exception{
        return new SendMailDTO(sendAO.getSendMailProps(), sendAO.getReceiver(), null, null, sendAO.getCont(), sendAO.getSubject(), null, sendAO.getSendMailProps().getAuthentication());
    }




    /**
     * @Title: addFileAffix 方法名
     * @Description: 添加附件
     * @param filePath
     * @return boolean
     */
    public boolean addFileAffix(String filePath){
        try {
            if (StringUtils.isNotBlank(filePath)) {
                MimeBodyPart attach = new MimeBodyPart();
                URL url = new URL(filePath);
                DataHandler dh = new DataHandler(url);
                attach.setDataHandler(dh);
                attach.setFileName(MimeUtility.encodeText(getFileName(dh.getName())));
                multipart.addBodyPart(attach);
                multipart.setSubType("mixed");

            }
        } catch (Exception e) {
            e.printStackTrace();
            LOG.info("添加附件异常: " + e.getMessage());
        }
        return  true;
    }



    /**
     * @Title: getFileName 方法名
     * @Description: 文件名
     * @param name
     * @return java.lang.String
     */
    public String getFileName(String name){
        name = name.substring(name.lastIndexOf("_") + 1);
        Pattern pattern = Pattern.compile(reg);
        Matcher matcher = pattern.matcher(name.toLowerCase());
        if (matcher.find()) {
            name = name.substring(0,name.lastIndexOf("."));
        }
        return name;
    }

	@Override
	public String toString() {
		return "SendMailDTO [reg=" + reg + ", mimeMessage=" + mimeMessage + ", session=" + session + ", properties="
				+ properties + ", multipart=" + multipart + "]";
	}



}
